package com.charmzenus.it.common.base;

import com.charmzenus.it.common.constants.CodeNumber;
import com.charmzenus.it.common.utils.ExceptionUtil;
import com.charmzenus.it.common.dto.response.BaseResponseDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.CompletionException;

/**
 * 这里是对异常捕捉
 */
@ControllerAdvice
@RestController
public class AppControllerActive {

    private static final Logger logger = LoggerFactory.getLogger(AppControllerActive.class);

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public BaseResponseDTO<String> errorHandler(Exception s) {

        if (s instanceof CompletionException) {

            if (s.getCause() instanceof MyErrorException) {
                MyErrorException ex = (MyErrorException) s.getCause();
                int code = ex.getCode();
                String message = ex.getMessage();
                return new BaseResponseDTO<>(code, message);
            }

        } else if (s instanceof MyErrorException) {
            MyErrorException ex = (MyErrorException) s;
            int code = ex.getCode();
            String message = ex.getMessage();
            return new BaseResponseDTO<>(code, message);
        } else if (s instanceof HttpRequestMethodNotSupportedException) {
            return new BaseResponseDTO<>(CodeNumber.error_normal, "接口请求方式异常");
        }
        logger.error(ExceptionUtil.errorMessage(s));
        return new BaseResponseDTO<>(CodeNumber.error_system_error, "服务器异常");
    }

    @RequestMapping(name = "/error")
    public BaseResponseDTO<String> error404() {
        return new BaseResponseDTO<>(CodeNumber.error_normal, "该接口不存在");
    }
}
